package com.zhuqi.service.impl;

import com.zhuqi.domain.SysUser;
import com.zhuqi.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.List;

/**
 * @author zhuqi
 * @version 1.0
 * @date 2021/3/25 18:59
 * 登录真正的方法
 */
@Service
public class SysUserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserMapper sysUserMapper;

    /**
     * 真实登录的方法
     * @param username 用户名
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 在前面的过滤器 security 已经帮我们判空过 这里无需对用户名进行判断,这里我们就查询用户就可以
        SysUser sysUser = sysUserMapper.selectUserByUsername(username);
        if (ObjectUtils.isEmpty(sysUser)){
            return null;
        }
        // 查询权限
        List<String> permissions = sysUserMapper.selectUserPermissionByUserId(sysUser.getUserid());
        if (!CollectionUtils.isEmpty(permissions)){
            sysUser.setAuthorities(permissions);
        }
        return sysUser;
    }
}
